package com.sakila.jaas;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.sakila.pojo.Staff;
import com.sakila.service.StaffService;
import com.sakila.vo.MyUser;

public class StaffAuthentication implements UserDetailsService{

	private final StaffService staffService;
	
	public StaffAuthentication(StaffService staffService) {
		this.staffService = staffService;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		Staff staff = staffService.findByUsername(username);
		if(staff == null){
			throw new UsernameNotFoundException("User '" + username + "' not found.");
		}
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		staff.getRoles().forEach(role ->
						authorities.add(new SimpleGrantedAuthority(role.getRole()))
		);
		/*for(Role role : staff.getRoles()){
			authorities.add(new SimpleGrantedAuthority(role.getRole()));
		}*/
		return new MyUser(staff.getUsername(), 
						staff.getPassword(), 
						authorities, staff);
	}

}
